<template>
  <div class="schedule-stats">
    <el-row :gutter="20">
      <!-- 统计卡片 - 只保留待处理、进行中、高优先级三项 -->
      <el-col :xs="8" :sm="8" :md="8" v-for="stat in stats" :key="stat.key">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: stat.color }">
              <el-icon size="24" color="#fff">
                <component :is="stat.icon" />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-title">{{ stat.title }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 今日日程 -->
    <el-row :gutter="20" class="today-schedules">
      <el-col :xs="24" :lg="12">
        <el-card class="schedule-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>今日日程</h3>
              <el-button type="primary" link @click="$router.push('/schedules')">
                查看全部
              </el-button>
            </div>
          </template>
          
          <div v-if="scheduleStore.todaySchedules.length === 0" class="empty-state">
            <el-icon size="48" color="#ddd"><Calendar /></el-icon>
            <p>今日暂无日程安排</p>
          </div>
          
          <div v-else class="schedule-list">
            <div
              v-for="schedule in scheduleStore.todaySchedules.slice(0, 5)"
              :key="schedule.id"
              class="schedule-item"
              :class="{ 'is-completed': schedule.status === 'completed' }"
            >
              <div class="schedule-time">
                {{ formatTime(schedule.start_time) }}
              </div>
              <div class="schedule-content">
                <div class="schedule-title">{{ schedule.title }}</div>
                <div class="schedule-meta">
                  <el-tag
                    :type="getPriorityTagType(schedule.priority || 'low')"
                    size="small"
                  >
                    {{ getPriorityText(schedule.priority || 'low') }}
                  </el-tag>
                  <el-tag
                    :type="getStatusTagType(schedule.status || 'pending')"
                    size="small"
                  >
                    {{ getStatusText(schedule.status || 'pending') }}
                  </el-tag>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 即将到来的日程 -->
      <el-col :xs="24" :lg="12">
        <el-card class="schedule-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>即将到来</h3>
              <el-button type="primary" link @click="$router.push('/schedules')">
                查看全部
              </el-button>
            </div>
          </template>
          
          <div v-if="scheduleStore.upcomingSchedules.length === 0" class="empty-state">
            <el-icon size="48" color="#ddd"><Clock /></el-icon>
            <p>暂无即将到来的日程</p>
          </div>
          
          <div v-else class="schedule-list">
            <div
              v-for="schedule in scheduleStore.upcomingSchedules"
              :key="schedule.id"
              class="schedule-item"
            >
              <div class="schedule-date">
                {{ formatDate(schedule.start_time) }}
              </div>
              <div class="schedule-content">
                <div class="schedule-title">{{ schedule.title }}</div>
                <div class="schedule-meta">
                  <el-tag
                    :type="getPriorityTagType(schedule.priority || 'low')"
                    size="small"
                  >
                    {{ getPriorityText(schedule.priority || 'low') }}
                  </el-tag>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 快速操作 -->
    <el-row class="quick-actions">
      <el-col :span="24">
        <el-card class="action-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>快速操作</h3>
            </div>
          </template>
          
          <div class="action-buttons">
            <el-button
              type="primary"
              :icon="Plus"
              size="default"
              @click="handleCreateSchedule"
            >
              新建日程
            </el-button>
            
            <el-button
              type="success"
              :icon="Check"
              size="default"
              @click="handleCompleteToday"
            >
              完成今日
            </el-button>
            
            <el-button
              type="info"
              :icon="Calendar"
              size="default"
              @click="$router.push('/schedules')"
            >
              查看日历
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 日程对话框 -->
    <ScheduleCreatOrModifyDialog
      v-model:visible="dialogVisible"
      :schedule="currentSchedule"
      mode="create"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Calendar,
  Clock,
  Plus,
  Check,
  Warning
} from '@element-plus/icons-vue'
import { useScheduleStore } from '@/stores/schedule'
import type { ScheduleResponse } from '@/api/models'
import ScheduleCreatOrModifyDialog from './ScheduleCreatOrModifyDialog.vue'

const scheduleStore = useScheduleStore()

// 状态
const dialogVisible = ref(false)
const currentSchedule = ref<ScheduleResponse | null>(null)

// 统计数据 - 只保留待处理、进行中、高优先级三项，移除change属性
const stats = computed(() => [
  {
    key: 'pending',
    title: '待处理',
    value: scheduleStore.stats.pending,
    icon: Clock,
    color: '#E6A23C'
  },
  {
    key: 'inProgress',
    title: '进行中',
    value: scheduleStore.stats.inProgress,
    icon: Clock,
    color: '#409EFF'
  },
  {
    key: 'highPriority',
    title: '高优先级',
    value: 0,
    icon: Warning,
    color: '#F56C6C'
  }
])

// 方法
const getPriorityTagType = (priority: string) => {
  const map: Record<string, string> = {
    low: 'info',
    medium: 'warning',
    high: 'danger'
  }
  return map[priority] || 'info'
}

const getPriorityText = (priority: string) => {
  const map: Record<string, string> = {
    low: '低',
    medium: '中',
    high: '高'
  }
  return map[priority] || '低'
}

const getStatusTagType = (status: string) => {
  const map: Record<string, string> = {
    pending: 'info',
    'in-progress': 'warning',
    completed: 'success',
    cancelled: 'danger'
  }
  return map[status] || 'info'
}

const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    pending: '待处理',
    'in-progress': '进行中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return map[status] || '待处理'
}

const formatTime = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    month: '2-digit',
    day: '2-digit'
  })
}

const handleCreateSchedule = () => {
  currentSchedule.value = null
  dialogVisible.value = true
}

const handleCompleteToday = async () => {
  try {
    const todaySchedules = scheduleStore.todaySchedules.filter(
      item => item.status !== 'completed'
    )
    
    if (todaySchedules.length === 0) {
      ElMessage.info('今日没有需要完成的日程')
      return
    }
    
    // 批量更新状态
    await Promise.all(
      todaySchedules.map(schedule =>
        scheduleStore.updateScheduleItemStatus(schedule.id, 'completed')
      )
    )
    
    ElMessage.success(`已完成 ${todaySchedules.length} 个日程`)
  } catch (error) {
    console.error('完成今日日程失败:', error)
  }
}

// 组件内部数据初始化方法 - 直接使用状态管理器
const initializeComponentData = async () => {
  try {
    // 使用状态管理器的loading状态
    scheduleStore.setLoading(true)
    
    // 并行获取统计数据和今日日程
    await Promise.all([
      scheduleStore.fetchScheduleStats(),
      scheduleStore.fetchTodaySchedules()
    ])
    
  } catch (error) {
    console.error('初始化组件数据失败:', error)
    ElMessage.error('数据加载失败')
  } finally {
    scheduleStore.setLoading(false)
  }
}

const handleDialogSuccess = () => {
  // 对话框成功后的处理
}

// 生命周期 - 组件内部初始化
onMounted(async () => {
  try {
    await initializeComponentData()
  } catch (error) {
    console.error('初始化组件数据失败:', error)
  }
})
</script>

<style scoped>
.schedule-stats {
  padding: 20px;
}

.stat-card {
  margin-bottom: 20px;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: var(--text-color);
  margin-bottom: 4px;
}

.stat-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

.stat-change {
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 2px;
}

.stat-change.up {
  color: #67C23A;
}

.stat-change.down {
  color: #F56C6C;
}

.today-schedules {
  margin-bottom: 20px;
}

.schedule-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color);
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #999;
}

.empty-state p {
  margin-top: 12px;
  font-size: 14px;
}

.schedule-list {
  max-height: 300px;
  overflow-y: auto;
}

.schedule-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.schedule-item:last-child {
  border-bottom: none;
}

.schedule-item.is-completed {
  opacity: 0.6;
}

.schedule-time,
.schedule-date {
  min-width: 60px;
  font-size: 12px;
  color: #999;
  margin-right: 12px;
}

.schedule-content {
  flex: 1;
}

.schedule-title {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-color);
  margin-bottom: 4px;
}

.schedule-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.schedule-location {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #666;
}

.quick-actions {
  margin-bottom: 20px;
}

.action-card {
  height: 100%;
}

.action-buttons {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stat-content {
    flex-direction: column;
    text-align: center;
    gap: 8px;
  }
  
  .stat-icon {
    width: 48px;
    height: 48px;
  }
  
  .stat-icon .el-icon {
    font-size: 24px;
  }
  
  .stat-value {
    font-size: 24px;
  }
  
  .stat-title {
    font-size: 14px;
  }
}

@media (max-width: 992px) {
  .today-schedules .schedule-card {
    margin-bottom: 16px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .card-header h3 {
    font-size: 18px;
  }
  
  .schedule-list {
    max-height: 250px;
  }
  
  /* 确保统计数据在同一行 */
  .el-col-xs-8 {
    width: 33.333333%;
  }
}

@media (max-width: 768px) {
  .schedule-stats {
    padding: 8px;
  }
  
  .stat-card {
    margin-bottom: 12px;
  }
  
  .stat-content {
    padding: 8px;
    flex-direction: column;
    text-align: center;
    gap: 6px;
  }
  
  .stat-icon {
    width: 40px;
    height: 40px;
  }
  
  .stat-icon .el-icon {
    font-size: 20px;
  }
  
  .stat-value {
    font-size: 20px;
  }
  
  .stat-title {
    font-size: 12px;
  }
  
  .schedule-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
    padding: 16px 0;
  }
  
  .schedule-time,
  .schedule-date {
    min-width: auto;
    margin-right: 0;
    font-size: 14px;
    font-weight: 500;
    color: #666;
  }
  
  .schedule-title {
    font-size: 16px;
    font-weight: 600;
  }
  
  .schedule-meta {
    flex-wrap: wrap;
    gap: 6px;
  }
  
  /* 快速操作按钮在同一行，但缩小尺寸 */
  .action-buttons {
    gap: 8px;
  }
  
  .action-buttons .el-button {
    width: auto;
    height: 36px;
    font-size: 12px;
    padding: 0 12px;
  }
  
  .empty-state {
    padding: 32px 16px;
  }
  
  .empty-state .el-icon {
    font-size: 40px;
  }
  
  .empty-state p {
    font-size: 13px;
  }
}

@media (max-width: 480px) {
  .schedule-stats {
    padding: 4px;
  }
  
  .stat-content {
    padding: 4px;
    gap: 4px;
  }
  
  .stat-icon {
    width: 32px;
    height: 32px;
  }
  
  .stat-icon .el-icon {
    font-size: 16px;
  }
  
  .stat-value {
    font-size: 16px;
  }
  
  .stat-title {
    font-size: 10px;
  }
  
  .schedule-item {
    padding: 12px 0;
  }
  
  .schedule-time,
  .schedule-date {
    font-size: 12px;
  }
  
  .schedule-title {
    font-size: 14px;
  }
  
  .schedule-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  /* 超小屏幕下按钮更紧凑 */
  .action-buttons {
    gap: 6px;
  }
  
  .action-buttons .el-button {
    height: 32px;
    font-size: 11px;
    padding: 0 8px;
  }
  
  .card-header h3 {
    font-size: 16px;
  }
  
  .schedule-list {
    max-height: 200px;
  }
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .stat-title {
    color: #999;
  }
  
  .schedule-item {
    border-bottom-color: #333;
  }
  
  .schedule-location {
    color: #999;
  }
}
</style>
